今天來介紹比較運算元。
is 和 is not operators 適用於任何 data type,因為比較的是物件的記憶體位置:
0.1 is (3+4j)
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
/var/folders/zq/_kqzvld5709fpk2pk5wrblkw0000gn/T/ipykernel_21125/2697711678.py:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
0.1 is (3+4j)
False
'a' is [1, 2, 3]
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
/var/folders/zq/_kqzvld5709fpk2pk5wrblkw0000gn/T/ipykernel_21125/3744826144.py:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
'a' is [1, 2, 3]
False
in 和 not in 適用於可迭代的物件,測試是否為成員之一:
1 in [1, 2, 3]
True
[1, 2] in [1, 2, 3]
False
[1, 2] in [[1,2], [2,3], 'abc']
True
'key1' in {'key1': 1, 'key2': 2}
True
1 in {'key1': 1, 'key2': 2}
False
== 和 != 比較雙方的值是否相等。
不同的 data type 仍可能可以用這兩個運算元,條件是它們有某種共通性。
比如,你可以比較 Fraction 和 Decimals 是否相等,但字串和整數則永不相等。
1 == '1'
False
from decimal import Decimal
from fractions import Fraction
Decimal('0.1') == Fraction(1, 10)
True
1 == 1 + 0j
True
True == Fraction(2, 2)
True
False == 0j
True
很多 data type 可以比較大小。但有些沒辦法,比如複數:
1 + 1j < 2 + 2j
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/maotingyang/Downloads/Comparison Operators.ipynb Cell 22 in <cell line: 1>()
----> <a href='vscode-notebook-cell:/Users/maotingyang/Downloads/Comparison%20Operators.ipynb#X31sZmlsZQ%3D%3D?line=0'>1</a> 1 + 1j < 2 + 2j
TypeError: '<' not supported between instances of 'complex' and 'complex'
混合 data type 比大小是可行的,但必須有邏輯:
1 < 'a'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/maotingyang/Downloads/Comparison Operators.ipynb Cell 24 in <cell line: 1>()
----> <a href='vscode-notebook-cell:/Users/maotingyang/Downloads/Comparison%20Operators.ipynb#X33sZmlsZQ%3D%3D?line=0'>1</a> 1 < 'a'
TypeError: '<' not supported between instances of 'int' and 'str'
Decimal('0.1') < Fraction(1, 2)
True
比較可以進行多個連鎖。
比如 a < b < c, Python 其實是在每對比較之間加上了 and: a < b and b < c
1 < 2 < 3
True
特別的是連鎖中的運算元不一定要一樣,可以混用:
a < b > c 等同於 a < b and b > c
不過這樣寫之前最好確認同事看得懂,否則也許後者可以更清楚的表達你想做什麼。
1 < 2 > -5 < 50 > 4
True
1 < 2 == Decimal('2.0')
True
import string
'A' < 'a' < 'z' > 'Z' in string.ascii_letters
True
好啦,今天就到這邊,我們明天見~
參考:Python 3: Deep Dive (Part 1 - Functional)